package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 个人银行账户 服务实现类
 * </p>
 *
 * @author wyy
 * @since 2025-08-10
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {

    /**
     * 保存或更新银行账户
     *
     * @param bankAccountUpsertReqDTO
     * @param type 2: 服务人员，3：机构
     */
    @Override
    @Transactional
    public BankAccount saveOrUpdate(BankAccountUpsertReqDTO bankAccountUpsertReqDTO, Integer type) {
        //1、获取当前登录用户id
        Long userId= UserContext.currentUserId();

        //2、将dto转换为实体
        //2.1、数据拷贝
        BankAccount bankAccount = BeanUtils.toBean(bankAccountUpsertReqDTO, BankAccount.class);
        //2.2、设置id、用户类型
        bankAccount.setUserId(userId);
        bankAccount.setUserType(type);

        //3、保存或更新
        this.saveOrUpdate(bankAccount);

        //4、返回结果
        return bankAccount;
    }

    /**
     * 获取当前用户银行账户信息
     *
     * @param type 2: 服务人员，3：机构
     * @return
     */
    @Override
    public BankAccountResDTO currentUserBankAccount(Integer type) {
        //1、获取当前登录用户id
        Long userId= UserContext.currentUserId();

        //2、根据id查询用户银行账户信息
        BankAccount bankAccount = this.lambdaQuery()
                .eq(BankAccount::getUserId, userId)
                .one();

        //3、将dto转换为实体
        //3.1、数据拷贝
        BankAccountResDTO bankAccountResDTO = BeanUtils.toBean(bankAccount, BankAccountResDTO.class);
        //3.2、设置用户id、用户类型
        bankAccountResDTO.setId(userId);
        bankAccountResDTO.setType(type);

        //4、返回结果
        return bankAccountResDTO;
    }
}
